package app.ui;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

import database.local.Business;
import database.local.Comment;
import database.local.Deal;
import database.local.PicturesUtil;
import database.local.Utils;

public class DealViewActivity extends Activity {
	// consts
	public static final String APP_ID = AndroAppActivity.APP_ID;
	//final int SHOW_PREFERENCES = AndroAppActivity.SHOW_PREFERENCES;
	// vars
	private Deal currentDeal;
	private Business currentBusiness;
	private TextView titleText, buisnessText, dealDateText, dealTimeText,
			dealAddressText, dealInfoText, avarageVoteText, totalVotesText;
	private RatingBar rateRatingBar, moneyRatingBar;
	private ListView commentsListView;
	private Button addReviewButton, findOnMap;
	// Facebook
	private Button likeButton;
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private ImageView dealImageView;
	private LinearLayout rateLayout;
	private Button expandButton;
	//private RatingBar ratingBar, moneyBar;
	private EditText commentTest;
	private ScrollView scrollView;
	private Button checkinButton;
	private Boolean isTextLong;
	
	// like and checkin buttons are reverse
	
	final static int LIKE = 1;
	final static int REVIEW = 2;
	final static int CHECKIN = 3;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_deal_layout);

		// get deal and business from bundle.
		Bundle b = getIntent().getBundleExtra("values");
		currentDeal = b.getParcelable("deal");
		currentBusiness = b.getParcelable("business");
		//
		// inflate fields
		inflateFields();

		// populate fields
		populateFields();

		// populate list
		ArrayList<Comment> tempArrayList = new ArrayList<Comment>(currentDeal.getComments());
		//commentsListView.setAdapter(new CommentsListArrayAdapter(this,
		//		tempArrayList));

//		
//		TextView emptyView = new TextView(this);
//		emptyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
//		emptyView.setText("No Comments");
//
//		commentsListView.setEmptyView(emptyView);

		// ----------------------set click listener for
		// buttons--------------------
		likeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkFacebookLoginAndCheckin(LIKE);
			}
		});
		
		checkinButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkFacebookLoginAndCheckin(CHECKIN);
			}
		});

		// toMap button
		findOnMap.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent toMapIntent = new Intent(DealViewActivity.this,
						AndroAppActivity.class);
				toMapIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

				Bundle bundle = new Bundle();
				bundle.putParcelable("business", currentBusiness);

				toMapIntent.putExtra("values", bundle);

				DealViewActivity.this.startActivity(toMapIntent);
			}
		});
		
		addReviewButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkFacebookLoginAndCheckin(REVIEW);
			}
		});


		// Set expandable panel listener
		
		// drawable;
		final Drawable drawDown = getResources().getDrawable(R.drawable.button_down);
				drawDown.setBounds(0,0,
				((int) drawDown.getIntrinsicWidth() ),((int) drawDown.getIntrinsicHeight()));
		
		final Drawable drawUp = getResources().getDrawable(R.drawable.button_up);
				drawUp.setBounds(0,0,
				((int) drawUp.getIntrinsicWidth() ),((int) drawUp.getIntrinsicHeight()));
				
		
//		expandButton.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View view) {
//				if (rateLayout.isShown()) {
//					rateLayout.setVisibility(View.GONE);
//					expandButton.setText("Rate It!");
//					expandButton.setCompoundDrawables(null, null, null, drawDown);
//					scrollView.fullScroll(ScrollView.FOCUS_UP);
//					expandButton.invalidate();
//					
//				} else {
//					rateLayout.setVisibility(View.VISIBLE);
//					expandButton.setText("Cancel");
//					expandButton.setCompoundDrawables(null, drawUp, null, null);
//					scrollView.pageScroll(ScrollView.FOCUS_DOWN);
//					expandButton.invalidate();
//
//					
//				}
//			}
//		});

//		addReviewButton.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View view) {
//				checkFacebookLoginAndCheckin(REVIEW);
//				rateLayout.setVisibility(View.GONE);
//				scrollView.fullScroll(ScrollView.FOCUS_UP);
//				expandButton.setText("Rate It!");
//				expandButton.setCompoundDrawables(null, null, null, drawDown);
//				expandButton.invalidate();
//
//			}
//		});

//		scrollView.fullScroll(ScrollView.FOCUS_UP);
		
	}

	// ------------------facebook-----------------
	private void checkFacebookLoginAndCheckin(int action) {
		if (!SessionStore.restore(mFacebook, this)) {
			Log.w("Veiw Deal", "Facebook session INVALID");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("You need to login with your facebook account!")
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Intent i = new Intent(
											DealViewActivity.this,
											PreferencesActivity.class);
									startActivity(i);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									return;
								}
							}).show();
		} else {
			Log.w("Veiw Deal", "Facebook session VALID");

			switch (action) {
			case LIKE:
				// Post on wall
				postOnWall();
				break;

			case REVIEW:
				openCommentScreen();
				break;
				
			case CHECKIN:
				Log.w("Veiw Deal", "Starting checkin...");
				PlaceCheckin();
				break;
			}
		}
	}

	public class placesCheckInListener extends BaseRequestListener {
		public void onComplete(final String response, final Object state) {
			Log.w("FacebookPost", "API Response: " + response);
		}

		public void onFacebookError(FacebookError error) {
			Log.w("FacebookPost", "Check-in Error: " + error.getMessage());
		}
	}
	
	public void PlaceCheckin() {
		Log.d("Tests", "Testing graph API wall post");
		Bundle params = new Bundle();
		params.putString("message", "Now enjoys deal " + currentDeal.getName()
				+ " at " + currentBusiness.getName());
		params.putString("description", currentDeal.getDealInfo());
		params.putString("link", currentBusiness.getWebsite());
		mAsyncRunner.request("me/feed", params, "POST",
				new WallPostRequestListener(), null);
		
		Toast.makeText(DealViewActivity.this, "You currently checked in", Toast.LENGTH_LONG)
		.show();
		
		AndroAppActivity context = AndroAppActivity.getInstance();
		if (context!=null)
			context.dbc.CheckIn(currentBusiness);
		else
		{
		OpeningActivity context_o = OpeningActivity.getInstance();
		if (context_o!=null)
			context_o.dbcc.CheckIn(currentBusiness);
		
		}
	}

	public void postOnWall() {
		Log.d("Tests", "Testing graph API wall post");
		Bundle params = new Bundle();
		params.putString("message", "Likes deal " + currentDeal.getName()
				+ " at " + currentBusiness.getName());
		params.putString("description", currentDeal.getDealInfo());
		params.putString("link", currentBusiness.getWebsite());
		mAsyncRunner.request("me/feed", params, "POST",
				new WallPostRequestListener(), null);
		
		Toast.makeText(DealViewActivity.this, "You posted on wall", Toast.LENGTH_LONG)
		.show();
		
		AndroAppActivity context = AndroAppActivity.getInstance();
		if (context!=null)
			context.dbc.Like(currentDeal);
		else
		{
		OpeningActivity context_o = OpeningActivity.getInstance();
		if (context_o!=null)
			context_o.dbcc.Like(currentDeal);
		}

	}

	public class WallPostRequestListener extends BaseRequestListener {

		public void onComplete(final String response) {

			Log.w("FacebookPost", "Done");
			Log.w("Facebook-Example", "Got response: " + response);
		}

		public void onComplete(String response, Object state) {
			Log.w("FacebookPost", "Done");
			Log.w("Facebook-Example", "Got response: " + response);
		}

	}

	// --------------------------------------------------------------------------

	protected void openCommentsList() {
		// TODO Auto-generated method stub

	}

	private void populateFields() {
		// TextView
		buisnessText.setText(currentBusiness.getName());

		ArrayList<String> daysList = Utils.bmp_to_weekdays_list(currentDeal
				.getDays_bitmap());
		String days = "";
		for (int i = 0; i <= daysList.size() - 1; i++) {
			days = days + daysList.get(i) + " ";
		}

		dealDateText.setText(days);
		if (currentDeal.getTime().equalsIgnoreCase("all")
				|| currentDeal.getTime().equalsIgnoreCase("")) {
			dealTimeText.setText("Always");
		} else {
			dealTimeText.setText(currentDeal.getTime()
					+ " - "
					+ Utils.computeTimeFromStrings(currentDeal.getTime(),
							currentDeal.getDelta_time()));
		}

		dealAddressText.setText(currentBusiness.getFullAddress());
		isTextLong = false;
		
		
		if (currentDeal.getDealInfo().length() <= 60)
			dealInfoText.setText(currentDeal.getDealInfo());
		else {
			dealInfoText.setText(currentDeal.getShortName(60));
		}
		
		dealInfoText.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isTextLong){
					dealInfoText.setText(currentDeal.getShortName(60));
					isTextLong = false;

				}
				else {
					dealInfoText.setText(currentDeal.getDealInfo());
					isTextLong = true;

				}
			}
		});
		
		//avarageVoteText.setText(getAlreadyRatedStr(currentDeal.getRate_num()));

		// RatingBars
		rateRatingBar.setRating(currentDeal.getRate());
		moneyRatingBar.setRating(currentDeal.getCostLevel());

		// Image
		dealImageView.setImageDrawable(PicturesUtil.getDealPicBig(currentDeal,
				this));
	}

	/**
	 * 
	 * @param rate_num
	 * @return proper string for the count (0, 1, more)
	 */
	private CharSequence getAlreadyRatedStr(int rate_num) {

		switch (rate_num) {
		case 0:
			return "No one has rated it.";
		case 1:
			return "1 Preson has already rated it!";
		default:
			return rate_num + " People have already rated it!";
		}

	}

	private void inflateFields() {
		// TextView
		
		buisnessText = (TextView) findViewById(R.id.deal_business_text);
		dealDateText = (TextView) findViewById(R.id.deal_date_text);
		dealTimeText = (TextView) findViewById(R.id.deal_time_text);
		dealAddressText = (TextView) findViewById(R.id.deal_business_address_text);
		dealInfoText = (TextView) findViewById(R.id.deal_deal_info_text);

		// RatingBar
		rateRatingBar = (RatingBar) findViewById(R.id.deal_review_rating_ratingbar);
		moneyRatingBar = (RatingBar) findViewById(R.id.deal_review_money_ratingbar);

		// Button
		likeButton = (Button) findViewById(R.id.view_deal_checkin_btn);
		checkinButton = (Button) findViewById(R.id.view_deal_like_btn);
		addReviewButton = (Button) findViewById(R.id.deal_comment_button);
		findOnMap = (Button) findViewById(R.id.deal_to_map_button);


		// Facebook
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);

		// Image
		dealImageView = (ImageView) findViewById(R.id.deal_image);

		// Rate panel
		//expandButton = (Button) findViewById(R.id.deal_comment_deal_expand);
		//rateLayout = (LinearLayout) findViewById(R.id.deal_comment_deal_layout);
		//ratingBar = (RatingBar) findViewById(R.id.deal_comment_deal_layout_rating);
		//moneyBar = (RatingBar) findViewById(R.id.deal_comment_deal_layout_costlevel);
		//commentTest = (EditText) findViewById(R.id.deal_comment_deal_layout_comment);
		//addReviewButton = (Button) findViewById(R.id.deal_comment_deal_layout_add_review_button);

		//Scroll View
		//scrollView = (ScrollView) findViewById(R.id.deal_scroll_view);
	}

	protected void openDealsList() {
		Intent openDealListsActivity = new Intent(this, DealsListView.class);
		Bundle bundle = new Bundle();

		bundle.putParcelable("business", currentBusiness);

		openDealListsActivity.putExtra("values", bundle);
		this.startActivity(openDealListsActivity);
	}
	
	protected void openCommentScreen(){
		Intent openCommentScreenActivity = new Intent(this, CommentListActivity.class );
		Bundle bundle = new Bundle();
		bundle.putParcelable("deal", currentDeal);
		
		openCommentScreenActivity.putExtra("values", bundle);
		this.startActivityForResult(openCommentScreenActivity, 0);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.deal_action_bar, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.deal_menu_business:
			openDealsList();
			return true;

		case R.id.deal_menu_report:
			AndroAppActivity context = AndroAppActivity.getInstance();
			context.dbc.fakeDeal(currentDeal);
			return true;
		}
		return false;
	}


}
